/**
 * 增值税发票进项管理 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Vat.IncomeMainForm", {
  extend: "PSI.AFX.Form.MainForm",

  config: {
    permission: null
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      items: [{
        tbar: me.getToolbarCmp(),
        id: me.buildId(me, "panelQueryCmp"),
        region: "north",
        height: 130,
        header: false,
        collapsible: true,
        collapseMode: "mini",
        border: 0,
        layout: {
          type: "table",
          columns: 5
        },
        bodyCls: "PSI-Query-Panel",
        items: me.getQueryCmp()
      }, {
        region: "center",
        layout: "border",
        border: 0,
        ...PSI.Const.BODY_PADDING,
        items: [
          {
            region: "center",
            layout: "fit",
            border: 0,
            items: me.getMainGrid(),
          }, {
            region: "south",
            layout: "border",
            height: "60%",
            split: true,
            collapsible: true,
            header: false,
            border: 0,
            items: [{
              region: "north",
              bodyStyle: "border-width:1px 1px 0px 1px",
              height: 40,
              border: 1,
              layout: {
                type: "table",
                columns: 5
              },
              bodyPadding: 10,
              items: me.getBillSummaryCmp()
            }, {
              region: "center",
              layout: "border",
              border: 0,
              items: [{
                region: "center",
                layout: "fit",
                border: 0,
                items: me.getDetailGrid()
              }, {
                region: "east",
                layout: "fit",
                width: "50%",
                split: true,
                border: 0,
                items: [{
                  title: "单据明细",
                  html:"<h3>TODO</h3>"
                }]
              }],
            }]
          }
        ]
      }]
    });

    me.callParent(arguments);

    me.editSummaryRef = PCL.getCmp(me.buildId(me, "editSummaryRef"));
    me.editSummarySupplier = PCL.getCmp(me.buildId(me, "editSummarySupplier"));
    me.editSummaryDT = PCL.getCmp(me.buildId(me, "editSummaryDT"));

    me.editQueryOrg = PCL.getCmp(me.buildId(me, "editQueryOrg"));
    me.editQueryStatus = PCL.getCmp(me.buildId(me, "editQueryStatus"));
    me.editQueryRef = PCL.getCmp(me.buildId(me, "editQueryRef"));
    me.editQueryFromDT = PCL.getCmp(me.buildId(me, "editQueryFromDT"));
    me.editQueryToDT = PCL.getCmp(me.buildId(me, "editQueryToDT"));
    me.editQuerySupplier = PCL.getCmp(me.buildId(me, "editQuerySupplier"));
    me.editQueryCategory = PCL.getCmp(me.buildId(me, "editQueryCategory"));

    me.comboCountPerPage = PCL.getCmp(me.buildId(me, "comboCountPerPage"));
    me.pagingToobar = PCL.getCmp(me.buildId(me, "pagingToobar"));

    me.panelQueryCmp = PCL.getCmp(me.buildId(me, "panelQueryCmp"));

    me._keyMapMain = PCL.create("PCL.util.KeyMap", PCL.getBody(), [{
      key: "N",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        // 判断权限
        if (me.getPermission().add != "1") {
          return;
        }

        me._onAddBill.apply(me, []);
      },
      scope: me
    }, {
      key: "Q",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }
        me.editQueryRef.focus();
      },
      scope: me
    }, {
      key: "H",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        const panel = me.panelQueryCmp;
        if (panel.getCollapsed()) {
          panel.expand();
        } else {
          panel.collapse();
        };
      },
      scope: me
    },
    ]);

    // AFX: 查询控件input List
    me.__editorList = [
      me.editQueryOrg, me.editQueryStatus, me.editQueryRef,
      me.editQueryFromDT, me.editQueryToDT, me.editQuerySupplier,
      me.editQueryCategory,
    ];

    me.queryCompanyList();
  },

  /**
   * @private
   */
  getToolbarCmp() {
    const me = this;

    let result = [];

    // 新建
    if (me.getPermission().add == "1") {
      result.push({
        iconCls: "PSI-tb-new",
        text: "新建发票记录 <span class='PSI-shortcut-DS'>Alt + N</span>",
        tooltip: me.buildTooltip("快捷键：Alt + N</span>"),
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler: me._onAddBill,
      })
    }

    // 变更
    let list = [];
    if (me.getPermission().edit == "1") {
      list.push({
        text: "编辑发票记录",
        scope: me,
        handler: me._onEditBill,
      })
    }
    if (me.getPermission().del == "1") {
      list.push({
        text: "删除发票记录",
        scope: me,
        handler: me._onDeleteBill,
      })
    }
    if (list.length > 0) {
      if (result.length > 0) {
        result.push("-");
      }

      result.push({
        text: "变更",
        ...PSI.Const.BTN_STYLE,
        menu: list
      });
    }

    // 电子发票
    list = [];
    if (me.getPermission().uploadPDF == "1") {
      list.push({
        text: "上传电子发票",
        scope: me,
        handler: me._onUploadPDF,
      })
    }
    if (me.getPermission().downloadPDF == "1") {
      list.push({
        text: "查看电子发票",
        scope: me,
        handler: me._onDownloadPDF,
      })
    }
    if (list.length > 0) {
      if (result.length > 0) {
        result.push("-");
      }

      result.push({
        text: "电子发票",
        ...PSI.Const.BTN_STYLE,
        menu: list
      });
    }

    // 核销
    if (me.getPermission().relCommit == "1") {
      if (result.length > 0) {
        result.push("-");
      }
      result.push({
        iconCls: "PSI-tb-commit",
        text: "核销",
        tooltip: me.buildTooltip("核销的前提条件：发票记录中的金额等于单据中的金额<br/><br/>详细说明见指南"),
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler: me._onCommit,
      })

    }

    // 指南
    // 关闭
    if (result.length > 0) {
      result.push("-");
    }
    result.push({
      iconCls: "PSI-tb-help",
      text: "指南",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        window.open(me.URL("Home/Help/index?t=vatIncome"));
      }
    }, "-", {
      iconCls: "PSI-tb-close",
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        me.closeWindow();
      }
    });

    result = result.concat(me.getPagination(), me.getShortcutCmp());

    return result;
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["|",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
   * 查询条件
   * 
   * @private
   */
  getQueryCmp() {
    const me = this;

    const modelName = me.buildModelName(me, "QueryOrg");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "name"]
    });

    return [{
      xtype: "container",
      height: 26,
      html: `<h2 style='margin-left:20px;margin-top:32px;color:#595959;display:inline-block'>增值税发票进项管理</h2>
                &nbsp;&nbsp;<span style='color:#8c8c8c'>采购业务中发生的增值税发票登记、核销管理</span>
                <div style='float:right;display:inline-block;margin:32px 0px 0px 20px;border-left:1px solid #e5e6e8;height:40px'>&nbsp;</div>
                `
    }, {
      id: me.buildId(me, "editQueryOrg"),
      labelWidth: 70,
      width: 490,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "组织机构",
      margin: "10, 0, 0, 0",
      xtype: "combobox",
      queryMode: "local",
      editable: false,
      valueField: "id",
      displayField: "name",
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        },
        select: {
          fn: me._onComboOrgSelect,
          scope: me
        },
      },
      colspan: 5,
    }, { xtype: "container" }, {
      id: me.buildId(me, "editQueryStatus"),
      xtype: "combo",
      queryMode: "local",
      editable: false,
      valueField: "id",
      labelWidth: 70,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "状态",
      margin: "5, 0, 0, 0",
      store: PCL.create("PCL.data.ArrayStore", {
        fields: ["id", "text"],
        data: [[-1, "全部"], [0, "待认证"], [1000, "已认证待核销"], [3000, "已核销"]]
      }),
      value: -1,
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryRef"),
      labelWidth: 100,
      width: 220,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "发票号 <span class='PSI-shortcut-DS'>Alt + Q</span>",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryFromDT"),
      xtype: "datefield",
      margin: "5, 0, 0, 0",
      format: "Y-m-d",
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "开票日期（起）",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryToDT"),
      xtype: "datefield",
      margin: "5, 0, 0, 0",
      format: "Y-m-d",
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "开票日期（止）",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, { xtype: "container" }, {
      id: me.buildId(me, "editQuerySupplier"),
      xtype: "psi_supplierfield",
      parentCmp: me,
      showModal: true,
      labelAlign: "right",
      labelSeparator: "",
      labelWidth: 70,
      margin: "5, 0, 0, 0",
      fieldLabel: "供应商",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryCategory"),
      xtype: "combo",
      queryMode: "local",
      editable: false,
      valueField: "id",
      labelWidth: 70,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "发票类型",
      matchFieldWidth: false,
      margin: "5, 0, 0, 0",
      store: PCL.create("PCL.data.ArrayStore", {
        fields: ["id", "text"],
        data: [[-1, "全部"], [1, "增值税专用发票"], [2, "增值税普通发票"], [3, "增值税普通发票(可抵扣)"]]
      }),
      value: -1,
      listeners: {
        specialkey: {
          fn: me.__onLastEditSpecialKey,
          scope: me
        }
      }
    }, {
      xtype: "container",
      colspan: 2,
      items: [{
        xtype: "button",
        text: "查询",
        cls: "PSI-Query-btn1",
        width: 100,
        height: 26,
        margin: "5 0 0 10",
        handler: me._onQuery,
        scope: me
      }, {
        xtype: "button",
        text: "清空查询条件",
        cls: "PSI-Query-btn2",
        width: 100,
        height: 26,
        margin: "5, 0, 0, 10",
        handler: me._onClearQuery,
        scope: me
      }, {
        xtype: "button",
        text: "隐藏工具栏 <span class='PSI-shortcut-DS'>Alt + H</span>",
        cls: "PSI-Query-btn3",
        width: 140,
        height: 26,
        iconCls: "PSI-button-hide",
        margin: "5 0 0 20",
        handler() {
          me.panelQueryCmp.collapse();
        },
        scope: me
      }]
    },];
  },

  /**
   * @private
   */
  getQueryParam() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();

    const result = {
      companyId,
      status: me.editQueryStatus.getValue(),
      category: me.editQueryCategory.getValue(),
    };

    const ref = me.editQueryRef.getValue();
    if (ref) {
      result.ref = ref;
    }

    const supplierId = me.editQuerySupplier.getIdValue();
    if (supplierId) {
      result.supplierId = supplierId;
    }

    const fromDT = me.editQueryFromDT.getValue();
    if (fromDT) {
      result.fromDT = PCL.Date.format(fromDT, "Y-m-d");
    }

    const toDT = me.editQueryToDT.getValue();
    if (toDT) {
      result.toDT = PCL.Date.format(toDT, "Y-m-d");
    }

    return result;
  },

  /**
   * @private
   */
  queryCompanyList() {
    const me = this;
    const store = me.editQueryOrg.getStore();
    const r = {
      url: me.URL("SLN0001/Vat/companyListForVatIncome"),
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (data.length > 0) {
            const companyId = data[0]["id"];
            me.editQueryOrg.setValue(companyId);

            me._onQuery.apply(me);
          }
        }
      }
    };
    me.ajax(r);
  },

  /**
   * 分页
   * 
   * @private
   */
  getPagination() {
    const me = this;
    const store = me.getMainGrid().getStore();
    const result = ["->", {
      id: me.buildId(me, "pagingToobar"),
      xtype: "pagingtoolbar",
      cls: "PSI-Pagination",
      border: 0,
      store: store
    }, "-", {
        xtype: "displayfield",
        fieldStyle: "font-size:13px",
        value: "每页显示"
      }, {
        id: me.buildId(me, "comboCountPerPage"),
        xtype: "combobox",
        cls: "PSI-Pagination",
        editable: false,
        width: 60,
        store: PCL.create("PCL.data.ArrayStore", {
          fields: ["text"],
          data: [["20"], ["50"], ["100"], ["300"],
          ["1000"]]
        }),
        value: 20,
        listeners: {
          change: {
            fn() {
              store.pageSize = me.comboCountPerPage.getValue();
              store.currentPage = 1;
              me.pagingToobar.doRefresh();
            },
            scope: me
          }
        }
      }, {
        xtype: "displayfield",
        fieldStyle: "font-size:13px",
        value: "张发票"
      }];

    return result;
  },

  getMainGrid() {
    const me = this;

    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "VatIncome");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "ref", "category", "dt", "supplierId", "supplierName", "inputUserName",
        "status", "goodsMoney", "inputDT",
        "tax", "moneyWithTax", "memo", "file", "fileDT"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 20,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0001/Vat/incomeList"),
        reader: {
          root: 'dataList',
          totalProperty: 'totalCount'
        }
      }
    });
    store.on("beforeload", () => {
      store.proxy.extraParams = me.getQueryParam();
    });
    store.on("load", (e, records, successful) => {
      if (successful) {
        me.gotoMainGridRecord(me._lastId);
      }
    });

    me._mainGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      viewConfig: {
        enableTextSelection: true
      },
      border: 1,
      columnLines: true,
      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [{
          xtype: "rownumberer",
          text: "#",
          width: 50
        }, {
          header: "状态",
          dataIndex: "status",
          width: 110,
          renderer(value) {
            if (value == 0) {
              return "<span style='color:red'>待认证</span>";
            } else if (value == 1000) {
              return "已认证待核销";
            } else if (value == 3000) {
              return "已核销";
            } else {
              return "";
            }
          }
        }, {
          header: "发票号",
          dataIndex: "ref",
          width: 150
        }, {
          header: "发票类型",
          dataIndex: "category",
          width: 140
        }, {
          header: "开票日期",
          dataIndex: "dt",
          width: 100
        }, {
          header: "供应商",
          dataIndex: "supplierName",
          width: 300
        }, {
          header: "金额",
          dataIndex: "goodsMoney",
          align: "right",
          xtype: "numbercolumn",
          width: 90
        }, {
          header: "税款",
          dataIndex: "tax",
          align: "right",
          xtype: "numbercolumn",
          width: 90
        }, {
          header: "价税合计",
          dataIndex: "moneyWithTax",
          align: "right",
          xtype: "numbercolumn",
          width: 90
        }, {
          header: "录入人",
          dataIndex: "inputUserName"
        }, {
          header: "录入时间",
          dataIndex: "inputDT",
          width: 150
        }, {
          header: "备注",
          dataIndex: "memo",
          width: 200
        }, {
          header: "电子发票？",
          dataIndex: "file",
          align: "center",
          width: 100,
          tooltip: me.buildTooltip("电子发票是否已上传到本系统？"),
        }, {
          header: "电子发票备份时间",
          dataIndex: "fileDT",
          width: 150
        }]
      },
      store: store,
      listeners: {
        select: {
          fn: me._onMainGridSelect,
          scope: me
        },
        itemdblclick: {
          fn: me.getPermission().edit == "1"
            ? me._onEditBill
            : PCL.emptyFn,
          scope: me
        }
      }
    });

    return me._mainGrid;
  },

  /**
   * @private
   */
  gotoMainGridRecord(id) {
    const me = this;

    const grid = me.getMainGrid();
    grid.getSelectionModel().deselectAll();
    const store = grid.getStore();
    if (id) {
      const r = store.findExact("id", id);
      if (r != -1) {
        grid.getSelectionModel().select(r);
      } else {
        grid.getSelectionModel().select(0);
      }
    } else {
      grid.getSelectionModel().select(0);
    }
  },

  /**
   * @private
   */
  refreshMainGrid(id) {
    const me = this;

    me.resetSummaryInput();

    me.pagingToobar.doRefresh();
    me._lastId = id;
  },

  /**
   * @private
   */
  _onAddBill() {
    const me = this;
    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      me.showInfo("请选择组织机构");
      return;
    }

    const store = me.editQueryOrg.getStore();
    const org = store.getById(companyId);
    const companyName = org?.get("name");

    const form = PCL.create("PSI.SLN0001.Vat.IncomeEditForm", {
      parentForm: me,
      companyId,
      companyName,
      renderTo: PSI.Const.RENDER_TO(),
    });

    form.show();
  },

  /**
   * @private
   */
  _onEditBill() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      me.showInfo("请选择组织机构");
      return;
    }

    const store = me.editQueryOrg.getStore();
    const org = store.getById(companyId);
    const companyName = org?.get("name");

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择要编辑的增值税发票进项记录");
      return;
    }
    const bill = item[0];

    const form = PCL.create("PSI.SLN0001.Vat.IncomeEditForm", {
      companyId,
      companyName,
      parentForm: me,
      entity: bill,
    });
    form.show();
  },

  /**
   * @private
   */
  _onDeleteBill() {
    const me = this;

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要删除的增值税发票进项记录");
      return;
    }

    const bill = item[0];

    if (bill.get("status") > 1000) {
      me.showInfo("当前增值税发票进项记录已经核销，不能删除");
      return;
    }

    const store = me.getMainGrid().getStore();
    let index = store.findExact("id", bill.get("id"));
    index--;
    let preIndex = null;
    const preItem = store.getAt(index);
    if (preItem) {
      preIndex = preItem.get("id");
    }

    const info = `请确认是否删除发票记录: <span style='color:red'>${bill.get("ref")}</span>`;
    const funcConfirm = () => {
      const el = PCL.getBody();
      el.mask("正在删除中...");
      const r = {
        url: me.URL("SLN0001/Vat/deleteVatIncome"),
        params: {
          id: bill.get("id")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.refreshMainGrid(preIndex);
              me.tip("成功完成删除操作", true);
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };

    me.confirm(info, funcConfirm);
  },

  /**
   * @private
   */
  _onQuery() {
    const me = this;

    me.getDetailGrid().getStore().removeAll();

    me.getMainGrid().getStore().currentPage = 1;
    me.refreshMainGrid();
  },

  /**
   * @private
   */
  _onClearQuery() {
    const me = this;

    me.editQueryRef.setValue(null);
    me.editQueryStatus.setValue(-1);
    me.editQueryCategory.setValue(-1);
    me.editQueryFromDT.setValue(null);
    me.editQueryToDT.setValue(null);
    me.editQuerySupplier.clearIdValue();

    me._onQuery();
  },

  /**
   * @private
   */
  _onUploadPDF() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      me.showInfo("请选择组织机构");
      return;
    }

    const store = me.editQueryOrg.getStore();
    const org = store.getById(companyId);
    const companyName = org?.get("name");

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要上传电子发票的进项记录");
      return;
    }

    const bill = item[0];
    const form = PCL.create("PSI.SLN0001.Vat.IncomeImportForm", {
      companyId,
      companyName,
      parentForm: me,
      entity: bill,
    });
    form.show();
  },

  /**
   * @private
   */
  _onDownloadPDF() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      me.showInfo("请选择组织机构");
      return;
    }

    const store = me.editQueryOrg.getStore();
    const org = store.getById(companyId);
    const companyName = org?.get("name");

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要增值税进项发票记录");
      return;
    }

    const bill = item[0];
    if (!bill.get("fileDT")) {
      const info = `发票号为 <span style='color:red'>${bill.get("ref")}</span> 的电子发票还没有上传`;
      me.showInfo(info);
      return;
    }

    const info = `当前组织机构：<span style='color:red'>${companyName}</span>
                  <br/>
                  请确认是否查看发票号为 <span style='color:red'>${bill.get("ref")}</span> 的电子发票？`;

    me.confirm(info, () => {
      const id = bill.get("id");
      window.open(me.URL(`/SLN0001/Vat/downloadIncomePDF?id=${id}`));
    });
  },

  /**
   * @private
   */
  getBillSummaryCmp() {
    const me = this;

    const fieldProps = {
      xtype: "textfield",
      readOnly: true,
      labelSeparator: "",
      labelAlign: "right",
    };
    return [{
      xtype: "container",
      height: 22,
      html: "<span style='padding:0px;margin:0px 0px 0px -5px;border-left: 5px solid #9254de'></span>",
    }, {
      id: me.buildId(me, "editSummaryRef"),
      fieldLabel: "发票号",
      fieldCls: "PSI-bill-summary-field",
      labelWidth: 50,
      value: "",
      ...fieldProps,
    }, {
      id: me.buildId(me, "editSummaryDT"),
      fieldLabel: "开票日期",
      labelWidth: 70,
      value: "",
      ...fieldProps,
    }, {
      id: me.buildId(me, "editSummarySupplier"),
      fieldLabel: "供应商",
      labelWidth: 70,
      value: "",
      colspan: 2,
      width: 430,
      ...fieldProps,
    },];
  },

  /**
   * @private
   */
  resetSummaryInput() {
    const me = this;

    me.editSummaryRef.setValue("");
    me.editSummarySupplier.setValue("");
    me.editSummaryDT.setValue("");
  },

  /**
   * @private
   */
  _onMainGridSelect() {
    const me = this;

    me.resetSummaryInput();

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {

      return;
    }

    const bill = item[0];

    me.editSummaryRef.setValue(bill.get("ref"));
    me.editSummaryDT.setValue(bill.get("dt"));
    me.editSummarySupplier.setValue(bill.get("supplierName"));

    me.refreshDetailGrid();
  },

  /**
   * @public
   */
  refreshDetailGrid(id) {
    const me = this;

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {

      return;
    }

    const bill = item[0];

    const grid = me.getDetailGrid();
    const el = grid.getEl();
    el?.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/Vat/incomeBillList"),
      params: {
        id: bill.get("id")
      },
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);

          if (store.getCount() > 0) {
            if (id) {
              const r = store.findExact("id", id);
              if (r != -1) {
                grid.getSelectionModel().select(r);
              }
            }
          }

        }

        el?.unmask();
      }
    });

  },

  /**
   * @private
   */
  getDetailGrid() {
    const me = this;

    if (me._detailGrid) {
      return me._detailGrid;
    }

    const modelName = me.buildModelName(me, "IncomeBillDetail");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "billRef", "billType", {
        name: "goodsMoney",
        type: "float"
      },]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._detailGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      tbar: [{ xtype: "displayfield", value: "<strong>发票与采购单据关联表</strong>" },
        "-", {
        iconCls: "PSI-tb-new-subentity",
        text: "新建关联",
        tooltip: me.buildTooltip("选择指定的采购单据，建立与当前发票的核销关系"),
        ...PSI.Const.BTN_STYLE,
        disabled: me.getPermission().relAdd == "0",
        handler: me._onAddIncomeBillRel,
        scope: me
      }, "-", {
        text: "删除关联",
        tooltip: me.buildTooltip("取消采购单据与当前发票的核销关系"),
        ...PSI.Const.BTN_STYLE,
        disabled: me.getPermission().relDelete == "0",
        handler: me._onDeleteIncomeBillRel,
        scope: me
      },],
      viewConfig: {
        enableTextSelection: true
      },
      features: [{
        ftype: "summary"
      }],
      columnLines: true,
      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [PCL.create("PCL.grid.RowNumberer", {
          text: "#",
          width: 40
        }), {
          header: "单据类型",
          dataIndex: "billType",
          width: 150,
        }, {
          header: "单据编号",
          dataIndex: "billRef",
          width: 150,
          renderer(value, md, record) {
            const billType = record.get("billType");
            let key = "";
            if (billType == "采购入库单") {
              key = "采购入库";
            } else if (billType == "采购退货出库单") {
              key = "采购退货出库";
            } else {
              // bug
              return value;
            }

            return `<a href='${PSI.Const.BASE_URL}SLN0001/Bill/viewIndex?fid=2039&refType=${encodeURIComponent(key)}&ref=${encodeURIComponent(value)}' 
                    target='_blank'>${value}
                  </a>`;
          },
          summaryRenderer() {
            return "合计";
          },
        }, {
          header: "金额",
          dataIndex: "goodsMoney",
          align: "right",
          xtype: "numbercolumn",
          width: 90,
          summaryType: "sum",
        },],
      },
      store
    });

    return me._detailGrid;
  },

  /**
   * @private
   */
  _onAddIncomeBillRel() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      me.showInfo("请选择组织机构");
      return;
    }

    const store = me.editQueryOrg.getStore();
    const org = store.getById(companyId);
    const companyName = org?.get("name");

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择增值税发票进项记录");
      return;
    }
    const bill = item[0];

    const form = PCL.create("PSI.SLN0001.Vat.SelectPurchaseForm", {
      companyId,
      companyName,
      parentForm: me,
      entity: bill,
    });
    form.show();
  },

  /**
   * @private
   */
  _onDeleteIncomeBillRel() {
    const me = this;

    const item = me.getDetailGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择要删除的关联单据项");
      return;
    }
    const relation = item[0];

    const store = me.getDetailGrid().getStore();
    let index = store.findExact("id", relation.get("id"));
    index--;
    let preIndex = null;
    const preItem = store.getAt(index);
    if (preItem) {
      preIndex = preItem.get("id");
    }

    const info = `请确认是否删除关联: <span style='color:red'>${relation.get("billType")} - ${relation.get("billRef")}</span>`;
    const funcConfirm = () => {
      const el = PCL.getBody();
      el.mask("正在删除中...");
      const r = {
        url: me.URL("SLN0001/Vat/deleteRelation"),
        params: {
          id: relation.get("id")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.refreshDetailGrid(preIndex);
              me.tip("成功完成删除操作");
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };

    me.confirm(info, funcConfirm);
  },

  /**
   * @private
   */
  _onCommit() {
    const me = this;

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择增值税发票进项记录");
      return;
    }
    const bill = item[0];

    const info = `请确认是否核销增值税发票进项记录?<br/>发票号：<span style='color:red'>${bill.get("ref")}</span>`;
    const store = me.getMainGrid().getStore();
    let index = store.findExact("id", bill.get("id"));
    index--;
    let preIndex = null;
    const preItem = store.getAt(index);
    if (preItem) {
      preIndex = preItem.get("id");
    }

    const funcConfirm = () => {
      const el = PCL.getBody();
      el.mask("正在处理中...");
      const r = {
        url: me.URL("SLN0001/Vat/commitVatIncome"),
        params: {
          id: bill.get("id")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.refreshMainGrid(preIndex);
              me.tip("成功完成核销操作", true);
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };

    me.confirm(info, funcConfirm);

  },

  /**
   * @private
   */
  _onComboOrgSelect() {
    const me = this;

    me._onQuery.apply(me);
  },
});
